package edu.cuit.avatar.generic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * 获取字段的泛型信息
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/19 10:17
 */
public class GenericFieldTest {
    //定义一个日志记录器
    private static final Logger LOG = LoggerFactory.getLogger(GenericFieldTest.class);
    private List<String> list;
    private Map<String, Integer> map;
    private int score;

    public static void main(String[] args) throws Exception {
        Class<GenericFieldTest> clazz = GenericFieldTest.class;
        Field listField = clazz.getDeclaredField("list");
        Field mapField = clazz.getDeclaredField("map");
        Field scoreField = clazz.getDeclaredField("score");

        LOG.info("main方法记录的info日志");
        LOG.error("main方法记录的error日志");

        if (listField.getGenericType() instanceof ParameterizedType pd){
            System.out.println("原始类型:" + pd.getRawType()); //获取原始类型
            System.out.println("参数类型:" + pd.getActualTypeArguments()[0].getTypeName()); //获取参数类型
        }

        if (mapField.getGenericType() instanceof ParameterizedType pd){
            System.out.println("原始类型:" + pd.getRawType()); //获取原始类型
            System.out.print("参数类型:" );
            //获取参数类型
            Type[] arguments = pd.getActualTypeArguments();
            for (Type para : arguments)
                System.out.println(para.getTypeName());
        }

        if(scoreField.getGenericType() instanceof ParameterizedType pd){
            System.out.println("是泛型字段");
        } else {
            System.out.println(scoreField.getGenericType());
        }
    }
}
